package com.xusiyan08.controller;

import com.xusiyan08.entity.Favorite;
import com.xusiyan08.entity.Item;
import com.xusiyan08.repository.FavoriteRepository;
import com.xusiyan08.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/favorites")
@CrossOrigin(origins = "*")
public class FavoriteController {

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Autowired
    private ItemService itemService;

    @PostMapping
    public ResponseEntity<?> addFavorite(@RequestBody Favorite favorite) {
        try {
            Favorite savedFavorite = favoriteRepository.save(favorite);
            return ResponseEntity.ok(savedFavorite);
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // Check if the exception is due to the unique_user_item constraint
            if (e.getMessage() != null && e.getMessage().contains("unique_user_item")) {
                // Return a specific response for duplicate entry
                return ResponseEntity.status(409).body("您已收藏过该商品！"); // 409 Conflict
            } else {
                // Re-throw other DataIntegrityViolationExceptions
                throw e;
            }
        } catch (Exception e) {
            // Handle other potential errors during save
            return ResponseEntity.status(500).body("收藏失败: " + e.getMessage());
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Favorite>> getUserFavorites(@PathVariable Long userId) {
        List<Favorite> favorites = favoriteRepository.findByUserId(userId);

        // Extract Items from Favorites and convert images to Base64
        List<Item> items = new java.util.ArrayList<>();
        for (Favorite favorite : favorites) {
            if (favorite.getItem() != null) {
                items.add(favorite.getItem());
            }
        }
        itemService.processItemListForImageDisplay(items); // Convert images to Base64

        return ResponseEntity.ok(favorites);
    }

    @DeleteMapping("/user/{userId}/item/{itemId}")
    public ResponseEntity<?> removeFavorite(@PathVariable Long userId, @PathVariable Long itemId) {
        favoriteRepository.deleteByUserIdAndItemId(userId, itemId);
        return ResponseEntity.ok("收藏已取消");
    }
}